<!-- 从业者-在线学习-播放页 -->
<template>
	<view class="video-course-container">
		<!-- 视频播放器占位 (16:9比例) -->
		<view class="video-player">
			<video 
			    id="myVideo" 
					class="myVideo" 
					:src="currentSrc" 
					:autoplay="true" 
					@timeupdate="handleTimeUpdate"
					@loadedmetadata="handleLoadedMetadata"
					@progress="currentProgress"  
					enable-danmu 
					danmu-btn 
					controls
					>
			</video>
		</view>

		<!-- 课程章节列表 --> 
				<!-- 章节列表 -->
				<view class="chapter-list">
					<!-- 遍历所有章节 -->
					<!-- 章节1 - 已学完 -->
					<view class="chapter-item completed" v-for="chapter in chaptersWithMaterials" >
						<view class="chapter-header">
							<text class="chapter-title">{{chapter.kcbinfo[0].bckcb_res_name}}</text>							
						</view>
					
						<view class="lesson-play"  v-for="material in chapter.materials" @click.stop="coursePlay(material.cycsd_code)">
							<view class="lesson-item">
								<view class="lesson-info">
									<text class="lesson-name">{{material.kcbinfo[0].bckcb_res_name }}</text>									
								</view>
								<view class="">
									<text class="lesson-fortry">{{material.kcbinfo[0].bckcb_res_fortry == 1 ? "试学" : "" }}</text>	
									<u-icon v-if="material.kcbinfo[0].bckcb_res_fortry == 1" name="play-circle-fill" color="#03B8CD" size="50"></u-icon>	
									<u-icon v-else name="lock-fill" color="#909399" size="50"></u-icon>
								</view>		
							</view>
							<view class="">
								<text class="lesson-duration">{{material.kcbinfo[0].bckcb_res_time}}</text>
								<text class="lesson-line"> | </text>
								<text class="lesson-status">{{material.cycsd_jindu == '0' ? "未开始" : material.cycsd_jindu == '100' ? "已完成" : material.cycsd_jindu+'%'}}</text>
							</view>							
							<view class="">
								<u-line color="#d7d7d8" margin="10rpx"></u-line>
							</view>			
						</view>						
					</view>		
				</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				duration: 0,  ////视频总时长
				currentTime: 0,  //视频播放当前时长
				currentPercentage: 0,  //视频播放当前进度
				serverPercentage: 0, ///服务端返回的视频进度
				bufferedPercentage: 0,  //视频缓冲进度 
				currentPlaying: '' ,// 当前播放的视频ID
				currentSrc: '', ///视频播放链接
				onlineCourseCode:'', ///在线课程明细code
				chapters:[]
			}
		},
		computed: {
			// chaptersList() {
			// 	return this.chapters.filter(item => String(item.bckcb_res_type) == '0')
			// },
			
			// // 获取每个章节下的课件
			// chaptersWithMaterials() {
			// 	return this.chaptersList.map(chapter => {
			// 		return {
			// 			...chapter,
			// 			materials: this.chapters.filter(item => 
			// 				String(item.bckcb_res_type) === '1' && item.bckcb_parentcode === chapter.bckcb_code
			// 			)
			// 		};
			// 	});				
			// },	
			chaptersList() {
				return this.chapters.filter(item => String(item.kcbinfo[0].bckcb_res_type) == '0')
			},
			
			// 获取每个章节下的课件
			chaptersWithMaterials() {
				return this.chaptersList.map(chapter => {
					return {
						...chapter,	
						materials: this.chapters.filter(item => 
							String(item.kcbinfo[0].bckcb_res_type) === '1' && item.kcbinfo[0].bckcb_parentcode === chapter.kcbinfo[0].bckcb_code
						)
					};
				});				
			},
			
		},
		onLoad(options) {
			this.onlineCourseCode = options.bccode;
		},
		onShow() {
			// 查询课程下的课程表章节、视频
			// this.starcyDetails()
			// 新的获取章节的接口
			this.startStudyDetails()
		},
		methods: {
			// 通过创建的开始学习的code，获取课程明细
			startStudyDetails() {
				this.$u.api.querybcstudy({
					"cycscode":this.onlineCourseCode //#在线学习课程的code
				}).then(res => {
					console.log('课程表-明细', res)
					this.chapters = []
					this.chapters = res.data.base_info
				})
			},		
			
			
			// 课程表，章节、视频
			starcyDetails() {
				this.$u.api.querybckcb({
					"bccode": this.onlineCourseCode ///#课程的code
				}).then(res =>{
					console.log('课程表：', res)
					this.chapters = []
					this.chapters = res.data.base_info;
					
				})
			},			
			
			playVideo(id) {
				// this.currentPlaying = id
				// uni.showToast({
				// 	title: `开始播放视频 ${id}`,
				// 	icon: 'none'
				// })
				// 实际开发中这里调用播放器API
			},
			pauseVideo(id) {
				uni.showToast({
					title: `暂停播放视频 ${id}`,
					icon: 'none'
				})
				// 实际开发中这里调用播放器API
			},
			// 开始播放课程 
			coursePlay(cycsdcode) {
				// let  bcbchapter = []
				let bcbchapter = this.chapters.filter(item => item.cycsd_code == cycsdcode);
				this.serverPercentage = parseInt(bcbchapter[0].cycsd_jindu) 
				console.log('课程表播放：', bcbchapter,cycsdcode)
				if(bcbchapter[0].kcbinfo[0].bckcb_res_uri[0].url !== "" && bcbchapter[0].kcbinfo[0].bckcb_res_fortry == 1) {
					this.currentPlaying = cycsdcode
					this.currentSrc = bcbchapter[0].kcbinfo[0].bckcb_res_uri[0].url
				} else {
					uni.showToast({
						title: `当前视频未开放或暂无视频`,
						icon: 'none'
					})
				}				
				 // this.currentSrc = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4'
				
			},
			// 加载完成后，获取视频的总时长
			handleLoadedMetadata(event) {
				this.duration = event.detail.duration;
				console.log('视频总时长:', this.duration, '秒');
				
			},
			// 播放视频，时间变化时触发，250ms触发一次，可以跟总时长算进度
			handleTimeUpdate(event) {
				this.currentTime = event.detail.currentTime;
				
				if (this.duration > 0) {
					this.currentPercentage = Math.min(
						Math.round((this.currentTime / this.duration) * 100),
						100
					);
				}
						
        console.log('进度', this.currentPercentage,this.serverPercentage)		
				// 只有新的进度大于服务端之前的进度时，才重新写接口
				if (this.currentPercentage > this.serverPercentage)	{
					// 每5秒调用一次（10000毫秒）
					if ( this.currentPercentage % 5 === 0) {
						
						this.updatePercent();
					}
				}

				
			},
			// 加载进度，是否显示缓冲
			currentProgress() {
				
				
			},
			// 向服务更新视频播放进度
			updatePercent() {
				this.$u.api.updatebcstudyjd({
					"cycsdcode": this.currentPlaying, ////#基础课程学习明细编号
					"cycsdjindu": String(this.currentPercentage),///#章节进度
				}).then(res => {
					console.log('updatePrecent:', res)
				})
			},
			
			beforeDestroy() {
				// 清理资源
				if (this.videoContext) {
					this.videoContext.pause();
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.video-course-container {
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.video-player {
		width: 100%;
		// aspect-ratio: 16/9;
		/* 16:9比例 */
		background-color: #000;
		position: relative;
		
		// 重新定义视频大小
		/deep/ uni-video {
			width: 100%;
			height: 220px;
		}

		// 重新定义视频大小
		/deep/ wx-video {
			width: 100%;
			height: 220px;
		}
	}

	.chapter-list {
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.chapter-item {
		padding: 24rpx;
		border-bottom: 1rpx solid #eee;

		&:last-child {
			border-bottom: none;
		}

		&.completed {
			background-color: #fff;
			opacity: 0.8;
		}

		&.locked {
			opacity: 0.6;

			.lesson-name,
			.lesson-duration {
				color: #c0c4cc !important;
			}
		}
	}

	.chapter-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.chapter-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.lesson-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 0;

		.lesson-info {
			display: flex;
			align-items: center;
			gap: 15rpx;

			.lesson-name {
				font-size: 28rpx;
				color: #333;
			}

			.lesson-status {
				font-size: 24rpx;
				color: #19be6b;
			}
		}

		.lesson-duration {
			font-size: 24rpx;
			color: #909399;
		}	

	}
	.lesson-line {
		margin: 0 10rpx;
	}
	
	.lesson-fortry{
		color:#F39742;
		margin-right: 10rpx;
		
	}
</style>